//
//  PreferentialInformationDetailViewController.m
//  CPICMobileServiceApp
//
//  Created by lizhiwei on 13-2-17.
//  Copyright (c) 2013年 lizhiwei. All rights reserved.
//

#import "PreferentialInformationDetailViewController.h"
#import "Config.h"
#import "UIImageView+WebCache.h"
#import "RCAlertViewUtil.h"
#import "NSString+SBJson.h"
#import "NSObject+SBJson.h"
#import "IFServiceEvaluation.h"
#import "AppDelegate.h"
#import <TencentOpenAPI/sdkdef.h>
#import <TencentOpenAPI/TencentOAuthObject.h>
#import "RCCaculateIntegral.h"

@interface PreferentialInformationDetailViewController ()

@end

@implementation PreferentialInformationDetailViewController
@synthesize titleLabel;
@synthesize code_id;
@synthesize img_Url;
@synthesize progress;
@synthesize detailcontent;
@synthesize BigImage;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self)
    {
        self.title = @"优惠详细信息";
        //self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg640X773@2x"]];
        self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc]initWithTitle:@"返回" style:(UIBarButtonItemStyleBordered) target:self action:@selector(back)];

    }
    return self;
}
-(void)back
{
}
-(id)initView:(NSString *)codeID;
{
    self.code_id=codeID;

    self = [super init];
    
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.autoresizesSubviews=TRUE;
    self.view.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin
    | UIViewAutoresizingFlexibleRightMargin |  UIViewAutoresizingFlexibleBottomMargin
    | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    
    IRow=0;
    NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];
    NSString *bgimage= [accountDefaults objectForKey:@"UserDefaultBgKindKey"];
    
    if ([bgimage isEqualToString:@"蓝色主题风格"])
    {
        ADD_BACKGROUND_BUTTONITEM(@"icon640X88@2x.png");
        ADD_LEFT_BUTTONITEM(@"back.png");
        ADD_TITLE_NAMEITEM(@"优惠信息详情");
        ADD_EXCHANGEHISTORY_BUTTONITEM(@"fenxiang.png");
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg640X773@2x"]];
    }
    else if([bgimage isEqualToString:@"棕色主题风格"])
    {
        ADD_BACKGROUND_BUTTONITEM(@"icon640X88_01@2x.png");
        ADD_LEFT_BUTTONITEM(@"back_01.png");
        ADD_TITLE_NAMEITEM(@"优惠信息详情");
        ADD_EXCHANGEHISTORY_BUTTONITEM(@"fenxiang.png");
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg640X773_01@2x"]];
    }
    else if([bgimage isEqualToString:@"重大节日皮肤"])
    {
        NSData *dataImg_02=[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_DATA_02];
        NSLog(@"-------找到%@",dataImg_02);
        NSData *dataImg_03=[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_DATA_03];
        NSData *dataImg_04=[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_DATA_04];
        
        NSURL *urlSkinImg_02=[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_URL_02]];
        NSURL *urlSkinImg_03=[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_URL_03]];
        NSURL *urlSkinImg_04=[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_URL_04]];
        NSLog(@"-------找到333%@",urlSkinImg_02);
        
        UIImageView * LogoImage = [[UIImageView alloc]init];
        [LogoImage setImageWithURL:urlSkinImg_03 success:^(UIImage *image)
         {
             NSData *imgData=UIImagePNGRepresentation(LogoImage.image);
             [[NSUserDefaults standardUserDefaults] setObject:imgData forKey:SKIN_IMG_DATA_03];
         } failure:^(NSError *error)
         {
             [self justShowMessage:@"更新皮肤失败!" title:@"提示"];
         }];
        
        LogoImage.image = [UIImage imageWithData:dataImg_03];
        LogoImage.frame = CGRectMake(0, 0, LogoImage.image.size.width/2, LogoImage.image.size.height/2);
        [self.view addSubview:LogoImage];
        
        //--------------------------
        UIButton * CallOutBtn1 = [UIButton buttonWithType:UIButtonTypeCustom];
        CallOutBtn1.frame = CGRectMake(10, 10, 109/2, 57/2);
        UIImageView * Back = [[UIImageView alloc]init];
        [Back setImageWithURL:urlSkinImg_02 success:^(UIImage *image)
         {
             NSData *imgData=UIImagePNGRepresentation(Back.image);
             [[NSUserDefaults standardUserDefaults] setObject:imgData forKey:SKIN_IMG_DATA_02];
         } failure:^(NSError *error)
         {
             [self justShowMessage:@"更新皮肤失败!" title:@"提示"];
         }];
        
        [Back setImage:[UIImage imageWithData:dataImg_02]];
        [CallOutBtn1 setImage:Back.image forState:UIControlStateNormal];
        [CallOutBtn1 addTarget:self action:@selector(ClickCallOutBtn) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:CallOutBtn1];
        //--------------------------
        
        ADD_TITLE_NAMEITEM(@"优惠信息详情");
        
        UIImageView *bgimage = [[UIImageView alloc]initWithFrame:CGRectMake(0,44, self.view.frame.size.width, self.view.frame.size.height-44)];
        [bgimage setImageWithURL:urlSkinImg_04 success:^(UIImage *image)
         {
             NSData *imgData=UIImagePNGRepresentation(bgimage.image);
             [[NSUserDefaults standardUserDefaults] setObject:imgData forKey:SKIN_IMG_DATA_04];
         } failure:^(NSError *error)
         {
             [self justShowMessage:@"更新皮肤失败!" title:@"提示"];
         }];
        
        [bgimage setImage:[UIImage imageWithData:dataImg_04]];
        [self.view addSubview:bgimage];
        [bgimage release];
        ADD_EXCHANGEHISTORY_BUTTONITEM(@"fenxiang.png");
    }
    //自定义标题
    titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0 , 244, 44)];
    titleLabel.backgroundColor = [UIColor clearColor];
    //设置Label背景透明
    titleLabel.font = [UIFont boldSystemFontOfSize:14.0];
    //设置文本字体与大小
    titleLabel.textColor = [UIColor whiteColor];
    //设置文本颜色
    titleLabel.textAlignment = UITextAlignmentLeft;
   // titleLabel.text = [AppDelegate app].InfoTitle;
    //设置标题
    self.navigationItem.titleView = self.titleLabel;
    
    
    //添加UITableview
    TableDetail = [[UITableView alloc]initWithFrame:CGRectMake(0, 44, self.view.frame.size.width, 100) style:UITableViewStyleGrouped];
	TableDetail.delegate = self;
	TableDetail.dataSource = self;
    
    TableDetail.opaque = NO;
    TableDetail.backgroundView = nil;
    TableDetail.autoresizingMask = UIViewContentModeTop;
    TableDetail.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
    TableDetail.scrollEnabled=NO;
    [self.view addSubview:TableDetail];
    
    CGRect imageframe=CGRectMake(0, 144, self.view.frame.size.width, self.view.frame.size.height-124);
    imageScrollView=[[UIScrollView alloc]initWithFrame:imageframe];
    
    //添加大图显示
    BigImage= [[UIImageView alloc]initWithFrame:CGRectMake(0, 144, 320, self.view.frame.size.height-124)];
    BigImage.image = [UIImage imageNamed:@"SmallImage50X50.png"];
    [self.view addSubview:BigImage];
    [BigImage release];
    
    [imageScrollView addSubview:BigImage];
    [self.view addSubview:imageScrollView];
    
    //添加详细的信息内容
    detailcontent= [[UITextView alloc]initWithFrame:CGRectMake(0, 144, 320, self.view.frame.size.height-124)];
    [detailcontent setEditable:NO];
    detailcontent.text = @"";
    [self.view addSubview:detailcontent];
    [detailcontent release];
    
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    myDelegate.bPreferentialInformation=TRUE;
    
    _permissions = [[NSArray arrayWithObjects:
                     kOPEN_PERMISSION_GET_USER_INFO,
                     kOPEN_PERMISSION_GET_SIMPLE_USER_INFO,
                     kOPEN_PERMISSION_ADD_ALBUM,
                     kOPEN_PERMISSION_ADD_IDOL,
                     kOPEN_PERMISSION_ADD_ONE_BLOG,
                     kOPEN_PERMISSION_ADD_PIC_T,
                     kOPEN_PERMISSION_ADD_SHARE,
                     kOPEN_PERMISSION_ADD_TOPIC,
                     kOPEN_PERMISSION_CHECK_PAGE_FANS,
                     kOPEN_PERMISSION_DEL_IDOL,
                     kOPEN_PERMISSION_DEL_T,
                     kOPEN_PERMISSION_GET_FANSLIST,
                     kOPEN_PERMISSION_GET_IDOLLIST,
                     kOPEN_PERMISSION_GET_INFO,
                     kOPEN_PERMISSION_GET_OTHER_INFO,
                     kOPEN_PERMISSION_GET_REPOST_LIST,
                     kOPEN_PERMISSION_LIST_ALBUM,
                     kOPEN_PERMISSION_UPLOAD_PIC,
                     kOPEN_PERMISSION_GET_VIP_INFO,
                     kOPEN_PERMISSION_GET_VIP_RICH_INFO,
                     kOPEN_PERMISSION_GET_INTIMATE_FRIENDS_WEIBO,
                     kOPEN_PERMISSION_MATCH_NICK_TIPS_WEIBO,
                     nil] retain];
    //NSString *appid = @"100389997";
    NSString *appid = @"222222";
    _tencentOAuth = [[TencentOAuth alloc] initWithAppId:appid
											andDelegate:self];
    //SinaWeibo *sinaweibo = [self sinaweibo];
}

-(void) ClickCallOutBtn
{
    
    [self.navigationController popViewControllerAnimated:YES];

}
-(void)ClickExchangeHistoryBtn
{
    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"分享" message:@"优惠信息分享" delegate:self cancelButtonTitle:@"取消分享" otherButtonTitles:@"分享到新浪微博",@"分享到腾讯微博", nil];
    alert.tag=4;
    [alert show];
    [alert release];
}
//- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
//{
//    if (alertView.tag==1) {
//        if (buttonIndex==0) {
//        }
//        else if(buttonIndex==1)
//        {
//            strShareContent=detailInfo;
//            [self shareSina];
//        }
//        else if(buttonIndex==2)
//        {
//            strShareContent=detailInfo;
//            [self shareQQ];
//        }
//        else
//        {
//
//    }
//}
-(void)caculateShareIntegral
{
    RCCaculateIntegral *rcCaculateIntegral=[[RCCaculateIntegral alloc]initCaculateIntegalView];
    [rcCaculateIntegral setCaculatRequest:@"61002"];
    [rcCaculateIntegral setHidden:YES];
    [self.view addSubview:rcCaculateIntegral];
    [rcCaculateIntegral release];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return IRow;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 40;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *Identifier=@"Identifier";
    UITableViewCell *cell=(UITableViewCell *)[TableDetail dequeueReusableCellWithIdentifier:Identifier];
    UILabel *labelTag= [[UILabel alloc] init];
    [labelTag setFrame:CGRectMake(20, 5, 80, 30)];
    [labelTag setFont:[UIFont systemFontOfSize:14.0]];
    [labelTag setBackgroundColor:[UIColor clearColor]];
    
    
    UILabel *labelDate = [[UILabel alloc] init];
    [labelDate setFrame:CGRectMake(100, 5, 200, 30)];
    [labelDate setFont:[UIFont systemFontOfSize:14.0]];
    [labelDate setBackgroundColor:[UIColor clearColor]];
    if (cell==nil)
    {
        cell=[[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Identifier]autorelease];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        cell.accessoryType = UITableViewCellAccessoryNone;
        
        cell.backgroundColor = [UIColor colorWithRed:239.0f/255.0f green:239.0f/255.0f blue:239.0f/255.0f alpha:1.0f];
        
        UIView *view = [[UIView alloc] initWithFrame:cell.frame];
        
        [view addSubview:labelTag];
        [view addSubview:labelDate];
        
        
        [labelTag release];
        [labelDate release];
        
        [cell addSubview:view];
        [view release];
    }
    if (indexPath.row==0) {
        labelTag.text=@"开始时间:";
        labelDate.text=beginDate;
    }
    else if(indexPath.row==1)
    {
        labelTag.text=@"结束时间:";
        labelDate.text=endDate;
    }
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    ClaimListViewController *claimListViewCtrl=[[ClaimListViewController alloc]init];
//    [self.navigationController pushViewController:claimListViewCtrl animated:YES];
//    [claimListViewCtrl release];
}

-(void)setRequest//向太保移动平台发送请求报文
{
//    NSString *strRequestCode=@"RequestCode=30301";
    NSMutableDictionary *dicRequest = [NSMutableDictionary dictionary];
    [dicRequest setObject:self.code_id forKey:@"offersId"];
    [dicRequest setObject:@"" forKey:@"userAccount"];
    NSString *strRequestJson=[dicRequest JSONRepresentation];
//    strRequestJson=[NSString stringWithFormat:@"&RequestData=%@",strRequestJson];
//    NSString *strUrl=[NSString stringWithFormat:@"%@%@%@",Server_Url,strRequestCode,strRequestJson];
//    NSString *strUrlEncod = [strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];//字符串编码转换
//    NSURL *myurl = [NSURL URLWithString:strUrlEncod];//This method expects URLString to contain any necessary percent escape codes, which are ‘:’, ‘/’, ‘%’, ‘#’, ‘;’, and ‘@’. Note that ‘%’ escapes are translated via UTF-8.
//    NSLog(@"请求报文为:%@",strUrl);
    ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:Server_Url_Form]];
    
    //设置需要POST的数据，这里提交两个数据，A=a&B=b
    [request setPostValue:@"30301" forKey:@"RequestCode"];
    [request setPostValue:strRequestJson forKey:@"RequestData"];
    
    [request setDelegate:self];
    [request setDidFailSelector:@selector(ResponseFail:)];
    [request setDidFinishSelector:@selector(ResonseSuccess:)];
    [request startAsynchronous];
    
    showProgress = YES;
    if (showProgress) {
        NSLog(@"88888");
        //[NSThread sleepForTimeInterval:1];
        progress= [[MBProgressHUD alloc]initWithView:self.view];
        [self.view addSubview:progress];
        [self.view bringSubviewToFront:progress];
        progress.labelText = @"查询中...";
        [progress show:YES];
        showProgress = NO;
    };
}

- (void)ResonseSuccess:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    NSString *responseString = [request responseString];
    NSLog(@"responseString %@",responseString);
    NSMutableDictionary *dictResponse=[responseString JSONValue];
    NSLog(@"dictResponse  %@",dictResponse);
    NSString *strContentType=[[NSString alloc]initWithFormat:@"%@",[dictResponse valueForKey:@"contentType"]];
    if ([strContentType isEqualToString:@"0"]) {
        BigImage.hidden=YES;
        detailcontent.hidden=NO;
        isImage=NO;
        isContent=YES;
    }
    else
    {
        BigImage.hidden=NO;
        detailcontent.hidden=YES;
        isImage=YES;
        isContent=NO;
    }
    beginDate=[dictResponse valueForKey:@"beginDate"];
    contextImgUrl=[dictResponse valueForKey:@"contextImgUrl"];
    detailInfo=[dictResponse valueForKey:@"detailInfo"];
    endDate=[dictResponse valueForKey:@"endDate"];
    title=[dictResponse valueForKey:@"title"];
    
    detailcontent.text=detailInfo;
    contextImgUrl=[[NSString alloc]initWithFormat:@"%@%@",Image_Url,contextImgUrl];
    NSString *imgURL=[contextImgUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    ImgUrl=imgURL;
    //[BigImage setImageWithURL:[NSURL URLWithString:imgURL] placeholderImage:[UIImage imageNamed:@"placeholder"]];
    NSURL *urlCompanyImg=[NSURL URLWithString:imgURL];
    [BigImage setImageWithURL:urlCompanyImg success:^(UIImage *image) {
        imageDown=BigImage.image;
        NSLog(@"image height:%f",imageDown.size.height);
        NSLog(@"image width:%f",imageDown.size.width);
        BigImage.frame=CGRectMake(0, 0, imageDown.size.width, imageDown.size.height);
        
        imageScrollView.contentSize=CGSizeMake(imageDown.size.width, imageDown.size.height);
        imageScrollView.scrollEnabled=YES;
    } failure:^(NSError *error) {
    }];

    
    IRow=2;
    [TableDetail reloadData];
    
//    NSString *serviceid =@"30201";
//    NSString *servicename =@"优惠信息";
//    IFServiceEvaluation *ifserviceevaluation =[[IFServiceEvaluation alloc]initView:serviceid withserviceName:servicename];
//    [ifserviceevaluation setIfServiceEvaluationRequest];
//    [ifserviceevaluation setHidden:YES];
//    [self.view addSubview:ifserviceevaluation];
//    [ifserviceevaluation release];
}

- (void)ResponseFail:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    NSLog(@"服务器连接失败!");
    [self justShowMessage:@"服务器连接失败" title:@"注意"];
}

static int post_image_status_times = 0;
static int post_status_times = 0;
-(void)shareSina
{
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    myDelegate.bKnowledgeInsurance=TRUE;
    
    AppDelegate *appMyDelegate=[[UIApplication sharedApplication]delegate];
    appMyDelegate.iLoginorAccountTag=1;
    
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    NSLog(@"%@", [keyWindow subviews]);
    
    
    SinaWeibo *sinaweibo = [self sinaweibo];
    
    if ([sinaweibo isAuthValid]) {
        //[self justShowMessage:@"你已经授权新浪微博" title:@"提示"];
        if (isImage==YES && isContent==NO) {
            if (!postImageStatusText)
            {
                post_image_status_times ++;
                [postImageStatusText release], postImageStatusText = nil;
//                postImageStatusText = [[NSString alloc] initWithFormat:@"CPICApp image status : %i %@", post_image_status_times, [NSDate date]];
                postImageStatusText = [[NSString alloc] initWithFormat:@"优惠啦!! %@,天天有惊喜《车E服》http://www.cpic.com.cn/cx/sz/ydkhd/index.shtml",title];
            }
            
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示"
                                                                message:[NSString stringWithFormat:@"你将分享以上内容到新浪微博 \"%@\"", postImageStatusText]
                                                               delegate:self cancelButtonTitle:@"Cancel"
                                                      otherButtonTitles:@"OK", nil];
            alertView.tag = 1;
            [alertView show];
            [alertView release];
        }
        else if(isImage==NO && isContent==YES)
        {
            if (!postStatusText)
            {
                post_status_times ++;
                [postStatusText release], postStatusText = nil;
                //postStatusText = [[NSString alloc] initWithFormat:@"CPICApp text status : %i %@%@", post_status_times, [NSDate date],strShareContent];
                postStatusText = [[NSString alloc] initWithFormat:@"优惠啦!! %@,%@,天天有惊喜《车E服》http://www.cpic.com.cn/cx/sz/ydkhd/index.shtml",title,strShareContent];
            }
            
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert"
                                                                message:[NSString stringWithFormat:@"你将分享以上内容到新浪微博 \"%@\"", postStatusText]
                                                               delegate:self cancelButtonTitle:@"Cancel"
                                                      otherButtonTitles:@"OK", nil];
            alertView.tag = 0;
            [alertView show];
            [alertView release];
        }
        
    }
    else
    {
        [sinaweibo logIn];
    }
    
}
- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1)
    {
        if (alertView.tag == 0)
        {
            // post status
            NSLog(@"保险知识%@",postStatusText);
            SinaWeibo *sinaweibo = [self sinaweibo];
            [sinaweibo requestWithURL:@"statuses/update.json"
                               params:[NSMutableDictionary dictionaryWithObjectsAndKeys:
                                       postStatusText, @"status",
                                       nil]
                           httpMethod:@"POST"
                             delegate:self];
            
        }
        else if (alertView.tag == 1)
        {
            // post image status
            
            SinaWeibo *sinaweibo = [self sinaweibo];
            
            [sinaweibo requestWithURL:@"statuses/upload.json"
                               params:[NSMutableDictionary dictionaryWithObjectsAndKeys:
                                       postImageStatusText, @"status",
                                       imageDown, @"pic", nil]
                           httpMethod:@"POST"
                             delegate:self];
            
        }
        else if(alertView.tag==2)
        {
            if (isImage==YES && isContent==NO) {
                TCAddShareDic *params = [TCAddShareDic dictionary];
                params.paramTitle = title;
                params.paramComment = @"优惠啦!!!天天有惊喜《车E服》(http://www.cpic.com.cn/cx/sz/ydkhd/index.shtml";
                //            params.paramSummary =  @"中国太平洋保险成立于1991年5月13日，总部设在上海，成功在A股和H股上市，旗下拥有太平洋寿险、太平洋产险、太平洋资产管理公司和长江养老保险等专业子公司，保持持续领先的市场地位。";
                //            params.paramImages = @"http://img1.gtimg.com/tech/pics/hv1/95/153/847/55115285.jpg";
                
                if ([ImgUrl isKindOfClass:[NSString class]]==YES) {
                    if (ImgUrl.length!=0) {
                        params.paramImages=ImgUrl;
                    }
                }
                else
                {
                    [self justShowMessage:@"图片地址无效" title:@"注意"];
                }
                
                params.paramUrl = @"(http://www.cpic.com.cn/cx/sz/ydkhd/index.shtml";
                
                if(![_tencentOAuth addShareWithParams:params]){
                    [self showInvalidTokenOrOpenIDMessage];
                }
            }
            
            if (isContent==YES && isImage==NO) {
                TCAddShareDic *params = [TCAddShareDic dictionary];
                params.paramTitle = title;
                params.paramComment = @"优惠啦!!!天天有惊喜《车E服》(http://www.cpic.com.cn/cx/sz/ydkhd/index.shtml";
                params.paramSummary = strShareContent;
                //            params.paramImages = @"http://img1.gtimg.com/tech/pics/hv1/95/153/847/55115285.jpg";
                
                params.paramUrl = @"http://www.cpic.com.cn/cpic/index.shtml";
                
                if(![_tencentOAuth addShareWithParams:params]){
                    [self showInvalidTokenOrOpenIDMessage];
                }
            }
            
        }
        else if(alertView.tag==3)
        {
            TCAddShareDic *params = [TCAddShareDic dictionary];
            params.paramTitle = title;
            params.paramComment = @"优惠啦!!!天天有惊喜《车E服》(http://www.cpic.com.cn/cx/sz/ydkhd/index.shtml";
            params.paramSummary = strShareContent;
            //            params.paramImages = @"http://img1.gtimg.com/tech/pics/hv1/95/153/847/55115285.jpg";
            
            params.paramUrl = @"http://www.cpic.com.cn/cpic/index.shtml";
            
            if(![_tencentOAuth addShareWithParams:params]){
                [self showInvalidTokenOrOpenIDMessage];
            }
        }
    }
    
    
    if (alertView.tag==4) {
        if (buttonIndex==0) {
        }
        else if(buttonIndex==1)
        {
            strShareContent=detailInfo;
            [self shareSina];
        }
        else if(buttonIndex==2)
        {
            strShareContent=detailInfo;
            [self shareQQ];
        }
        else
        {
        }
    }
}
- (void)showInvalidTokenOrOpenIDMessage{
    UIAlertView *alert = [[[UIAlertView alloc]initWithTitle:@"api调用失败" message:@"可能授权已过期，请重新获取" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil] autorelease];
    [alert show];
}
/**
 * Called when the add_share has response.
 */
- (void)addShareResponse:(APIResponse*) response {
	if (response.retCode == URLREQUEST_SUCCEED)
	{
		
		[self caculateShareIntegral];
		NSMutableString *str=[NSMutableString stringWithFormat:@""];
		for (id key in response.jsonResponse) {
			[str appendString: [NSString stringWithFormat:@"%@:%@\n",key,[response.jsonResponse objectForKey:key]]];
		}
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"操作成功" message:nil
							  
													   delegate:self cancelButtonTitle:@"我知道啦" otherButtonTitles:nil];
		[alert show];
        [alert release];
		
		
		
	}
	else {
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"操作失败" message:[NSString stringWithFormat:@"%@", response.errorMsg]
							  
													   delegate:self cancelButtonTitle:@"我知道啦" otherButtonTitles: nil];
		[alert show];
        [alert release];
	}
}

-(void)shareQQ
{
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    myDelegate.bKnowledgeInsurance=TRUE;
    
    if([_tencentOAuth isSessionValid])
    {
        if (isImage==YES && isContent==NO) {
            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"你将分享以上内容到腾讯微博" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            alert.tag=2;
            [alert show];
            [alert release];
        }
        else if(isContent==YES && isImage==NO)
        {
            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"你将分享以上内容到腾讯微博" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            alert.tag=3;
            [alert show];
            [alert release];
        }
        
    }
    else
    {
        [_tencentOAuth authorize:_permissions inSafari:NO];
    }
    
}

-(void)setBindCheckRequest//向太保移动平台发送请求报文
{
    //    NSString *strRequestCode=@"RequestCode=62102";
    NSMutableDictionary *dicRequest = [NSMutableDictionary dictionary];
    if (QQopenId.length!=0) {
        [dicRequest setValue:QQopenId forKey:@"UserId"];
    }
    else
    {
        [dicRequest setValue:@"" forKey:@"UserId"];
    }
    [dicRequest setValue:@"2" forKey:@"bindingType"];
    NSString *strRequestJson=[dicRequest JSONRepresentation];
    ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:Server_Url_Form]];
    //设置需要POST的数据，这里提交两个数据，A=a&B=b
    [request setPostValue:@"62102" forKey:@"RequestCode"];
    [request setPostValue:strRequestJson forKey:@"RequestData"];
    
    [request setDelegate:self];
    [request setDidFailSelector:@selector(ResponseBindCheckFail:)];
    [request setDidFinishSelector:@selector(ResonseBindCheckSuccess:)];
    [request startAsynchronous];
    
    showProgress = YES;
    if (showProgress) {
        NSLog(@"88888");
        // [NSThread sleepForTimeInterval:1];
        progress= [[MBProgressHUD alloc]initWithView:self.view];
        [self.view addSubview:progress];
        [self.view bringSubviewToFront:progress];
        progress.labelText = @"查询中...";
        [progress show:YES];
        showProgress = NO;
    }
}

- (void)ResonseBindCheckSuccess:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    NSString *responseString = [request responseString];
    NSLog(@"responseString %@",responseString);
    NSMutableDictionary *dictResponse=[responseString JSONValue];
    NSLog(@"dictResponse  %@",dictResponse);
    NSMutableDictionary *dictHead=[dictResponse valueForKey:@"head"];
    NSString *strResult= [[NSString alloc] initWithFormat:@"%@",[dictHead objectForKey:@"success"]];
    NSLog(@"strResult%@",strResult);
    NSString *strUserAccount1=[dictResponse objectForKey:@"userAccount"];
    // if ([strResult isEqualToString:@"1"]) {
    if (strUserAccount1.length!=0) {
        //[self justShowMessage:@"登录成功" title:nil];
        bindingQQ=YES;
        [self checkQQAuth];
    }
    else
    {
        //[self justShowMessage:@"登录失败" title:nil];
        bindingQQ=NO;
        [self checkQQAuth];
        
    }
    
}
-(void)checkQQAuth
{
    if([_tencentOAuth isSessionValid])
    {
        if (bindingQQ==NO) {
            [self justShowMessage:@"你还没绑定本系统账户,请到绑定页面进行绑定" title:@"确定"];
        }
//        else
//        {
            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"你将分享以上内容到腾讯微博" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            alert.tag=2;
            [alert show];
            [alert release];
//        }
    }
    else
    {
        [_tencentOAuth authorize:_permissions inSafari:NO];
    }
    
    
}

- (void)ResponseBindCheckFail:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    NSLog(@"服务器连接失败!");
    [self justShowMessage:@"服务器连接失败" title:@"注意"];
}


- (SinaWeibo *)sinaweibo
{
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    return delegate.sinaweibo;
}
- (void)storeAuthData
{
    SinaWeibo *sinaweibo = [self sinaweibo];
    
    NSDictionary *authData = [NSDictionary dictionaryWithObjectsAndKeys:
                              sinaweibo.accessToken, @"AccessTokenKey",
                              sinaweibo.expirationDate, @"ExpirationDateKey",
                              sinaweibo.userID, @"UserIDKey",
                              sinaweibo.refreshToken, @"refresh_token", nil];
    [[NSUserDefaults standardUserDefaults] setObject:authData forKey:@"SinaWeiboAuthData"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [self justShowMessage:@"授权成功" title:nil];
}
#pragma mark - SinaWeibo Delegate

- (void)sinaweiboDidLogIn:(SinaWeibo *)sinaweibo
{
    NSLog(@"sinaweiboDidLogIn userID = %@ accesstoken = %@ expirationDate = %@ refresh_token = %@", sinaweibo.userID, sinaweibo.accessToken, sinaweibo.expirationDate,sinaweibo.refreshToken);
    [self storeAuthData];
}

- (void)sinaweiboDidLogOut:(SinaWeibo *)sinaweibo
{
    NSLog(@"sinaweiboDidLogOut");
    
}

- (void)sinaweiboLogInDidCancel:(SinaWeibo *)sinaweibo
{
    NSLog(@"sinaweiboLogInDidCancel");
}

- (void)sinaweibo:(SinaWeibo *)sinaweibo logInDidFailWithError:(NSError *)error
{
    NSLog(@"sinaweibo logInDidFailWithError %@", error);
}

- (void)sinaweibo:(SinaWeibo *)sinaweibo accessTokenInvalidOrExpired:(NSError *)error
{
    NSLog(@"sinaweiboAccessTokenInvalidOrExpired %@", error);
    
}

#pragma mark - SinaWeiboRequest Delegate

- (void)request:(SinaWeiboRequest *)request didFailWithError:(NSError *)error
{
    if ([request.url hasSuffix:@"users/show.json"])
    {
        [userInfo release], userInfo = nil;
    }
    else if ([request.url hasSuffix:@"statuses/user_timeline.json"])
    {
        [statuses release], statuses = nil;
    }
    else if ([request.url hasSuffix:@"statuses/update.json"])
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert"
                                                            message:[NSString stringWithFormat:@"Post status \"%@\" failed!", postStatusText]
                                                           delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alertView show];
        [alertView release];
        
        NSLog(@"Post status failed with error : %@", error);
    }
    else if ([request.url hasSuffix:@"statuses/upload.json"])
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert"
                                                            message:[NSString stringWithFormat:@"Post image status \"%@\" failed!", postImageStatusText]
                                                           delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alertView show];
        [alertView release];
        
        NSLog(@"Post image status failed with error : %@", error);
    }
    
    
    
}

- (void)request:(SinaWeiboRequest *)request didFinishLoadingWithResult:(id)result
{
    [self caculateShareIntegral];
    if ([request.url hasSuffix:@"users/show.json"])
    {
        [userInfo release];
        userInfo = [result retain];
    }
    else if ([request.url hasSuffix:@"statuses/user_timeline.json"])
    {
        [statuses release];
        statuses = [[result objectForKey:@"statuses"] retain];
    }
    else if ([request.url hasSuffix:@"statuses/update.json"])
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert"
                                                            message:@"分享成功"
                                                           delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alertView show];
        [alertView release];
        
        [postStatusText release], postStatusText = nil;
    }
    else if ([request.url hasSuffix:@"statuses/upload.json"])
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert"
                                                            message:@"分享成功"
                                                           delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alertView show];
        [alertView release];
        
        [postImageStatusText release], postImageStatusText = nil;
    }
    
}
- (void)storeAuthQQ
{
    
    NSDictionary *authData = [NSDictionary dictionaryWithObjectsAndKeys:
                              QQAccessToken, @"QQAccessToken",
                              QQopenId, @"QQopenId", nil];
    
    [[NSUserDefaults standardUserDefaults] setObject:authData forKey:@"Dict_QQAuthData"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
#pragma mark - TencentSessionDelegate
/**
 * Called when the user successfully logged in.
 */
- (void)tencentDidLogin {
	// 登录成功
	[self justShowMessage:@"QQ登录成功" title:nil];
    
    
    if (_tencentOAuth.accessToken
        && 0 != [_tencentOAuth.accessToken length])
    {
        QQAccessToken = _tencentOAuth.accessToken;
        QQopenId=_tencentOAuth.openId;
        [self storeAuthQQ];
        [self setBindCheckRequest];
    }
    else
    {
        QQAccessToken = @"登录不成功 没有获取accesstoken";
    }
    
}

/**
 * Called when the user dismissed the dialog without logging in.
 */
- (void)tencentDidNotLogin:(BOOL)cancelled
{
	if (cancelled){
        [self justShowMessage:@"用户取消登录" title:nil];
	}
	else {
        [self justShowMessage:@"登录失败" title:nil];
	}
	
}
/**
 * Called when the notNewWork.
 */
-(void)tencentDidNotNetWork
{
    [self justShowMessage:@"无网络连接，请设置网络" title:nil];
}

/**
 * Called when the logout.
 */
-(void)tencentDidLogout
{
    [self justShowMessage:@"退出登录成功，请重新登录" title:nil];
    QQAccessToken = @"";
    
    
}



-(void)dealloc
{

    [super dealloc];

}


@end
